import { Injectable } from "@nestjs/common";
import { ListRoleDto } from "./dto/list-role.dto";
import { InjectRepository } from "@nestjs/typeorm";
import { User } from "../user/entities/user.entity";
import { Role } from "./entities/role.entity";
import { Like, Repository, DataSource, In } from "typeorm";
import { ResponseUtils } from "../common/utils/esponse.util";

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role)
    private roleRepository: Repository<Role>,
    @InjectRepository(User)
    private userRepository: Repository<User>,

    private dataSoure: DataSource
  ) {}
  async findList(query: ListRoleDto) {
    const { page, pageSize, keyword } = query;
    const [userList, total] = await this.roleRepository.findAndCount({
      where: {
        name: Like(`%${keyword}%`)
      },
      relations: ["users"],
      take: pageSize,
      skip: (page - 1) * pageSize
    });
    return ResponseUtils.success({
      data: userList,
      total: total
    });
  }

  async updateUser(body: { id: string; userIds: string[] }) {
    const { id, userIds } = body;
    const role = await this.roleRepository.findOne({ where: { id: id }, relations: ["users"] });
    if (!role) return ResponseUtils.error("角色不存在，请刷新数据");
    const { userIds: roleUserIds } = role;
    const ids = !roleUserIds || roleUserIds.length == 0 ? userIds : roleUserIds.concat(userIds);

    const users = await this.userRepository.find({ where: { id: In(ids) } });

    role.users = users;

    await this.roleRepository.save(role);
    return ResponseUtils.success(null, "更新成功");
    // const { userIds: roleUserIds, id: roleId } = role;
    // console.log(roleId);
    // const users = await this.userRepository.find({ where: { id: In(roleUserIds) } });
    // console.log(users);

    // 创建事务
    // const queryRunner = this.dataSoure.createQueryRunner();
    // await queryRunner.connect();
    // await queryRunner.startTransaction();
    // try {
    //   const { userIds: roleUserIds } = role;
    //   const ids = !roleUserIds || roleUserIds.length == 0 ? roleUserIds : roleUserIds.concat(userIds);

    //   const users = await this.userRepository.find({ where: { id: In(ids) } });
    //   console.log(users);
    //   if (!users || users.length == 0) {
    //     ResponseUtils.error("当前绑定的用户被删除，请刷新数据");
    //     await queryRunner.release();
    //   } else {
    //     users.forEach(async user => {
    //       console.log(user);
    //       if (!user.roleIds || user.roleIds.length == 0) {
    //         user.roleIds = [id];
    //       } else {
    //         if (!user.roleIds.includes(id)) {
    //           user.roleIds.push(id);
    //         }
    //       }
    //       await this.userRepository.save(user);
    //     });
    //   }

    //   role.userIds = userIds;

    //   await this.roleRepository.save(role);

    //   await queryRunner.commitTransaction();
    //   return ResponseUtils.success(null, "更新成功");
    // } catch (error) {
    //   console.log(error);
    //   // 回滚事务
    //   await queryRunner.rollbackTransaction();
    // } finally {
    //   //  释放事务
    //   await queryRunner.release();
    // }

    // await this.roleRepository.update(id, { userIds: userIds.join(",") });
  }
  // create(createRoleDto: CreateRoleDto) {
  //   return 'This action adds a new role';
  // }
  // findAll() {
  //   return `This action returns all role`;
  // }
  // findOne(id: number) {
  //   return `This action returns a #${id} role`;
  // }
  // update(id: number, updateRoleDto: UpdateRoleDto) {
  //   return `This action updates a #${id} role`;
  // }
  // remove(id: number) {
  //   return `This action removes a #${id} role`;
  // }
}
